#-*- encoding: utf-8 -*-
#
# Copyright (C) 2008 Håvard Gulldahl.
#
# Licensed under the GNU Public License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.gnu.org/licenses/gpl-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
 

import sys

import bitpimlite.vcard


class VCards(bitpimlite.vcard.VCards):
  def next(self):
    # find vcard start
    field=value=None
    for field,value in self.vfile:
        if (field,value)!=(["BEGIN"], "VCARD"):
            continue
        found=True
        break
    if (field,value)!=(["BEGIN"], "VCARD"):
        # hit eof without any BEGIN:vcard
        raise StopIteration()
    # suck up lines
    lines=[]
    for field,value in self.vfile:
        if (field,value)!=(["END"], "VCARD"):
            lines.append( (field,value) )
            continue
        break
    if (field,value)!=(["END"], "VCARD"):
        raise VFileException("There is a BEGIN:VCARD but no END:VCARD")
    return VCard(lines)

IM_X_list = (u'X-MSN', u'X-ICQ', u'X-AIM', u'X-JABBER', u'X-GTALK', u'X-YAHOO',
             u'X-GROUPWISE', u'X-GADUGADU') # Evolution

IM_MESSAGING_list = (u'X-messaging/icq-All', u'X-messaging/xmpp-All', u'X-messaging/msn-All',
  u'X-messaging/gadu-All') # KDE


class VCard(bitpimlite.vcard.VCard):

  def getfield(self, field):
    try:
      ret = [ self._data[field], ]
    except KeyError:
      return []
    i = 2
    while True:
      try:
        ret.append(self._data['%s%s' % (field, i)])
      except KeyError:
        break
      i+=1
    return ret

  def _default_field(self, field, value, result):
    ff=field[0].upper().split(".")
    f0=ff[0]
    f1=ff[1] if len(ff)>1 else ''

    if 'X-MESSAGING' in field[0].upper() or f0 in IM_X_list or f1 in IM_X_list:
      return self._field_IM(field, value, result)
    else:
      return bitpimlite.vcard.VCard._default_field(self, field, value, result)

  def _field_IM(self, field, value, result):
    print field, value
    ff=field[0].upper().split(".")
    f0=ff[0]
    f1=ff[1] if len(ff)>1 else ''

    munge = {'XMPP' : 'JABBER'}

    if 'X-MESSAGING' in f0:
      protocol = f0[len('X-MESSAGING/'):].split('-')[0]
      protocol = munge.get(protocol, protocol) # Translate to 'standard' identifiers
      value = value.replace(u'\xee\x84\xa0', u'@') # KDE separates nick and network ...
    elif 'X-MESSAGING' in f1:
      protocol = f1[len('X-MESSAGING/'):].split('-')[0]
      protocol = munge.get(protocol, protocol)
      value = value.replace(u'\xee\x84\xa0', u'@') # ... with a nul byte
    elif f0 in IM_X_list:
      protocol = f0[len('X-'):]
    elif f1 in IM_X_list:
      protocol = f1[len('X-'):]

    value=self.unquote(value)
    # work out the types
    types=[]
    for f in field[1:]:
      if f.startswith("TYPE="):
        ff=f[len("TYPE="):].split(",")
      else: ff=[f]
      types.extend(ff)

    _type="other"
    for t in types:
      if t=="HOME": _type="home"
      if t=="WORK": _type="business"

    preferred="PREF" in types

    im={'address': value, 'type': _type, 'protocol': protocol}
    self._setvalue(result, "im", im, preferred)

  #_field_LABEL=_field_ignore        # we use the ADR field instead
  #_field_BDAY=_field_ignore         # not stored in bitpim
  #_field_ROLE=_field_ignore         # not stored in bitpim
  #_field_CALURI=_field_ignore       # not stored in bitpim
  #_field_CALADRURI=_field_ignore    # variant of above
  #_field_FBURL=_field_ignore        # not stored in bitpim
  #_field_REV=_field_ignore          # not stored in bitpim
  #_field_KEY=_field_ignore          # not stored in bitpim
  #_field_SOURCE=_field_ignore       # not stored in bitpim (although arguably part of serials)
  #_field_PHOTO=_field_ignore        # contained either binary image, or external URL, not used by BitPim

  def _field_BDAY(self, field, value, result):
    result[self._getfieldname("birthday", result)]=self.unquote(value)

  def _field_TEL(self, field, value, result):
    if not 'HOME 'in field[1:] and not 'WORK' in field[1:]:
      field.append('HOME')
    return bitpimlite.vcard.VCard._field_TEL(self, field, value, result)

if __name__ == '__main__':
  import sys
  f = bitpimlite.vcard.VFile(file(sys.argv[1]))
  print [x for x in VCards(f)]
  print x.getfield('phone')
  print x.getfield('name')
  print x.getfield('im')
